package com.ww.juc.countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 使用原理
 * 1、创建CountDownLatch并设置计数器值；
 * 2、启动多线程并且调用CountDownLatch实例的countDown()方法；
 * 3、主线程调用await()方法，这样主线程的操作就会在这个方法上阻塞，直到其他线程完成各自的任务，count值为0，停止阻塞，主线程继续执行；
 *
 * @author wanggw
 * @date 2024-09-15 17:47:22
 */
public class CountDownLatchModule {

    // 线程数
    private static int N = 10;

    private static int countDownLatchTimeout = 5;

    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(N);

        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

        for (int i = 0; i < N; i++) {
            cachedThreadPool.execute(() -> {
                try {
                    System.out.println(Thread.currentThread().getName() + "干点事");
                } finally {
                    latch.countDown();
                }
            });
        }

        System.out.println("主线程执行中...");
        try {
            latch.await(countDownLatchTimeout, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            System.out.println("countDownLatch：" + latch.toString());
        }

        System.out.println("主线程执行完成,准备退出");
        cachedThreadPool.shutdown();
    }
}
